package com.innovation.ic.cc.base.handler.cc;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.Claim;
import com.google.common.base.Strings;
import com.innovation.ic.cc.base.pojo.constant.Constants;
import com.innovation.ic.cc.base.pojo.constant.model.DefaultUserConstants;
import com.innovation.ic.cc.base.pojo.variable.AuthenticationUser;

import java.util.Map;

/**
 * 认证用户处理器
 */
public class AuthenticationUserHandler {
    /**
     * 将token对象转换为接收用户信息vo类对象
     * @param token erp返回的token对象
     * @return 返回接收用户信息
     */
    public static AuthenticationUser toAuthenticationUser(String token) {
        AuthenticationUser authenticationUser = null;

        if(!Strings.isNullOrEmpty(token)){
            authenticationUser = new AuthenticationUser();
            //解密token
            Map<String, Claim> claims = JWT.decode(token).getClaims();

            // 用户id
            authenticationUser.setId(claims.get(Constants.ID).asString());

            // 账号
            authenticationUser.setUsername(claims.get(DefaultUserConstants.USER_NAME).asString());

            // 名称
            authenticationUser.setName(claims.get(DefaultUserConstants.LOWER_NAME).asString());

            // 职位：1表示经理，2表示员工
            authenticationUser.setPosition((claims.get(DefaultUserConstants.POSITION_NAME).asString()));

            //手机号
            authenticationUser.setPhone(claims.get(DefaultUserConstants.PHONE_NAME).asString());

            //邮箱
            authenticationUser.setEmail(claims.get(DefaultUserConstants.EMAIL_NAME).asString());

            //状态
            authenticationUser.setStatus(claims.get(DefaultUserConstants.STATUS_NAME).asString());

            //创建日期
            authenticationUser.setCreateDate(claims.get(DefaultUserConstants.CREATE_DATE_NAME).asString());

            //供应商id
            authenticationUser.setEpId(claims.get(DefaultUserConstants.EP_ID_NAME).asString());

            //主账号 账号
            authenticationUser.setEpName(claims.get(DefaultUserConstants.EP_NAME).asString());

            // token过期时间
            authenticationUser.setExpiration(claims.get(DefaultUserConstants.EXPIRATION).asString());

            // 是否是主账号
            String ismain = claims.get(DefaultUserConstants.IS_MAIN).asString();
            if(!Strings.isNullOrEmpty(ismain)){
                authenticationUser.setIsMain(Integer.valueOf(ismain));
            }

            // token
            authenticationUser.setToken(token);
        }

        return authenticationUser;
    }
}